<?php
/*
 * @Author: your name
 * @Date: 2021-11-22 11:47:59
 * @LastEditTime: 2022-03-06 23:55:09
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \property\app\Http\Middleware\WriteLog.php
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\common_model\Common;


class WriteLog
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle(Request $request, Closure $next)
  {
    $routerName = $request->route()->getName();
    if ($routerName) {
      $path = $request->path();
      $firstUrlPath = explode('/', $path)[0];
      if ($firstUrlPath == 'adminApi') {
        $tableName = 'operation_log';
        $tableInsertData = [
          'operation_content' => addslashes(json_encode($_POST['REQUEST_ALL'][$request->method()], JSON_UNESCAPED_UNICODE)),   //操作的内容
          'path'   => $path,                                   //操作的路由
          'method' => $request->method(),                      //操作的方法
          'ip'     => $_SERVER['X-REAL-IP'],                   //操作的IP
          'operation_id' =>   \App\Http\Controllers\admin_controller\BaseController::getAdminId_(),         //操作人id
          'create_time' => date('Y-m-d H:i:s'),
          'describe' =>  str_replace('/', '', $routerName),
        ];
      } else if ($firstUrlPath == 'crmApi') {
        $tableName = 'crm_operation_log';
        $tableInsertData = [
          'operation_content' => addslashes(json_encode($_POST['REQUEST_ALL'][$request->method()], JSON_UNESCAPED_UNICODE)),   //操作的内容
          'path'   => $path,                                   //操作的路由
          'method' => $request->method(),                      //操作的方法
          'ip'     => $_SERVER['X-REAL-IP'],                   //操作的IP
          'operation_id' =>   \App\Http\Controllers\crm\BaseController::getAdminId_(),         //操作人id
          'create_time' => date('Y-m-d H:i:s'),
          'describe' =>  str_replace('/', '', $routerName),
        ];
      }

      if (isset($tableName) && isset($tableInsertData)) {
        \co::create(function () use ($tableName, $tableInsertData) {
          \Swoole\Coroutine\System::sleep(0.2);
          Common::insert($tableName, $tableInsertData);   //添加日志
        });
      }
    }
    return $next($request); //$next($request)本质上就是response
  }


  // public function 
}
